<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.templateId ? $t('crud.addBtn') : $t('sysManagement.modify')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'English' ? '220px' : '130px'"
      @submit.prevent
      @keyup.enter="onSubmit(dataFormRef)"
    >
      <el-form-item
        :label="$t('platform.notifyConten') + '：'"
        prop="message"
      >
        <el-input
          v-model="dataForm.message"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('platform.notifyType') + '：'"
        prop="templateTypeList"
      >
        <el-checkbox-group
          v-model="dataForm.templateTypeList"
          @change="checkboxChange"
        >
          <el-checkbox :label="1">
            {{ $t('platform.msgNotifyFree') }}
          </el-checkbox>
          <el-checkbox
            v-if="type === 1"
            :label="2"
          >
            {{ $t('platform.publicNotify') }}
          </el-checkbox>
          <el-checkbox
            v-if="type === 1"
            :label="3"
          >
            {{ $t('platform.appletMessage') }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-if="boxcheckedOne === 1"
        :label="$t('platform.smsTemplateCode') + '：'"
        prop="templateCode"
      >
        <el-input
          v-model="dataForm.templateCode"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        v-if="type === 1 && boxcheckedTwo === 1"
        :label="$t('platform.publicTemplateCode') + '：'"
        prop="mpCode"
      >
        <el-input
          v-model="dataForm.mpCode"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="close"
        >
          {{ $t('remindPop.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit(dataFormRef)"
        >
          {{ $t('remindPop.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList', 'close'])

const dataFormRef = ref(null)

const visible = ref(false)
const isCheck = ref(false)
const isConfirm = ref(false)
const boxcheckedOne = ref(0) // 1:显示短信  0:不显示
const boxcheckedTwo = ref(0) // 1:显示公众号 0:不显示
const type = ref(1) // 1:用户消息  2：商家消息
const dataForm = ref({
  templateId: null,
  sendType: null,
  templateTypeList: [],
  message: null,
  templateCode: null,
  mpCode: null,
  createTime: null,
  templateTypes: ''
})
const dataRule = reactive({
  sendType: [{ required: true, message: $t('platform.seleMsgType'), trigger: 'blur' }],
  message: [{ required: true, message: $t('platform.notifyContenNoNull'), trigger: 'blur' }]
})
const options = [
  {
    value: 1,
    label: $t('platform.orderPay')
  },
  {
    value: 2,
    label: $t('platform.paySuccNotify')
  },
  {
    value: 3,
    label: $t('platform.merAgreeReturn')
  },
  {
    value: 4,
    label: $t('order.refusedRefund')
  },
  {
    value: 5,
    label: $t('platform.wriOffRem')
  },
  {
    value: 6,
    label: $t('platform.shipRem')
  },
  {
    value: 7,
    label: $t('platform.groupFailRem')
  },
  {
    value: 8,
    label: $t('platform.groupSuccRem')
  },
  {
    value: 9,
    label: $t('platform.startGroupRem')
  },
  {
    value: 10,
    label: $t('platform.memUpRem')
  },
  {
    value: 11,
    label: $t('platform.timeoutRem')
  },
  {
    value: 12,
    label: $t('platform.register')
  },
  {
    value: 13,
    label: $t('platform.login')
  },
  {
    value: 14,
    label: $t('platform.updatePassword')
  },
  {
    value: 15,
    label: $t('platform.vaild')
  },
  {
    value: 102,
    label: $t('platform.confirmReceRem')
  },
  {
    value: 103,
    label: $t('platform.buyerRefundRem')
  },
  {
    value: 104,
    label: $t('platform.buyerReturnRem')
  },
  {
    value: 105,
    label: $t('platform.buyerPaySuccessRem')
  }
]

const msg = text => {
  ElMessage({
    message: text,
    type: 'error',
    duration: 1500
  })
  isCheck.value = true
}

const checkboxChange = val => {
  if (val) dataForm.value.templateTypes = val.join(',')
  boxcheckedOne.value = 0
  boxcheckedTwo.value = 0
  dataForm.value.templateTypeList.forEach(item => {
    if (item === 1) {
      boxcheckedOne.value = 1
    } else if (item === 2) {
      boxcheckedTwo.value = 1
    }
  })
}

const updateType = () => {
  const sendType = dataForm.value.sendType
  options.forEach(item => {
    if (sendType === item.value) {
      type.value = sendType > 100 ? 2 : 1
      if (sendType === 12 || sendType === 13 || sendType === 14 || sendType === 15) {
        type.value = 3
      }
      if (type.value === 2 || type.value === 3) {
        dataForm.value.templateTypeList.forEach(temp => {
          if (temp === 1) {
            dataForm.value.templateTypeList = [1]
          }
        })
      }
    }
  })
}

// 表单提交
const onSubmit = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (!valid) return
    isCheck.value = false
    dataForm.value.templateTypeList.forEach(type => {
      if (type === 1 && dataForm.value.templateCode == null) {
        msg($t('platform.notifyTempNoNull'))
      }
      if (type === 2 && dataForm.value.mpCode == null) {
        msg($t('platform.errorTip2'))
      }
    })
    if (isCheck.value || isConfirm.value) {
      return
    }
    isConfirm.value = true
    http({
      url: http.adornUrl('/admin/notifyTemplate'),
      method: dataForm.value.templateId ? 'put' : 'post',
      data: http.adornData(dataForm.value)
    })
      .then(() => {
        ElMessage({
          message: $t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            close()
            emit('refreshDataList')
          }
        })
      })
      .catch(() => {
        isConfirm.value = false
      })
  })
}

const close = () => {
  visible.value = false
  emit('close')
}

const init = templateId => {
  isConfirm.value = false
  isCheck.value = false
  dataForm.value.templateTypeList = []
  dataForm.value.templateId = templateId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.value.templateId) {
      http({
        url: http.adornUrl('/admin/notifyTemplate/info/' + dataForm.value.templateId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data
        updateType()
        checkboxChange()
        dataForm.value.templateTypeList = data.templateTypeList
      })
    }
  })
}

defineExpose({ init })
</script>
